package com.wl.zk.onoffline;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Client {


    ArrayList<String> infos = new ArrayList<String>();

    ZkClient zkClient = null;
    private void getConnet(){
        zkClient = new ZkClient("linux121:2181,linux122:2181,linux123:2181");

        List<String> childs = zkClient.getChildren("/servers");

        for (String child : childs) {
            Object o = zkClient.readData("/servers/" + child);
            infos.add(String.valueOf(o));
        }

        zkClient.subscribeChildChanges("/servers", new IZkChildListener() {
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                ArrayList<String> lists = new ArrayList<String>();

                for (String path : currentChilds) {

                    Object o = zkClient.readData("/servers" + path);
                    lists.add(String.valueOf(o));
                }

                infos = lists;
            }
        });

    }

    public void sendRequest() throws IOException {

        Random random = new Random();
        int i = random.nextInt(infos.size());
        String ipPort = infos.get(i);
        String[] arr = ipPort.split(":");


        Socket socket = new Socket(arr[0],Integer.valueOf(arr[1]));
        OutputStream out = socket.getOutputStream();
        InputStream in = socket.getInputStream();

        out.write("query time ".getBytes());
        out.flush();

        byte[] b = new byte[1024];
        in.read(b);

        System.out.println("client端接收到server:+" + ipPort + "+返回结果： " + new String(b));

        in.close();
        out.close();
        socket.close();

    }

    public static void main(String[] args) throws InterruptedException {
        Client client = new Client();
        client.getConnet();

        while (true){
            try {
                client.sendRequest();
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    client.sendRequest();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            Thread.sleep(2000);
        }
    }

}
